package cn.gpnusz.oliverwiki.service;

import cn.gpnusz.oliverwiki.entity.Category;
import cn.gpnusz.oliverwiki.entity.CategoryExample;
import cn.gpnusz.oliverwiki.mapper.CategoryMapper;
import cn.gpnusz.oliverwiki.req.CategorySaveReq;
import cn.gpnusz.oliverwiki.resp.CategoryQueryResp;
import cn.gpnusz.oliverwiki.util.SnowFlake;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @description 电子书分类业务层
 * @author h0ss
 * @date 2021/9/6 13:17 
 */
@Service
public class CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SnowFlake snowFlake;


    /**
     * 查询全部电子书分类数据的业务方法
     *
     * @return : cn.gpnusz.oliverwiki.resp.PageResp<cn.gpnusz.oliverwiki.resp.CategoryQueryResp>
     * @author h0ss
     */
    public List<CategoryQueryResp> getAll() {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        return getCategoryResp(categoryList);
    }

    /**
     * 新增或编辑电子书分类的业务方法
     *
     * @param categorySaveReq : 保存的电子书分类数据
     * @author h0ss
     */
    public void save(CategorySaveReq categorySaveReq) {
        Category category = new Category();
        BeanUtils.copyProperties(categorySaveReq, category);
        // 判断是新增还是编辑
        if (category.getId() != null) {
            CategoryExample categoryExample = new CategoryExample();
            CategoryExample.Criteria criteria = categoryExample.createCriteria();
            criteria.andIdEqualTo(category.getId());
            categoryMapper.updateByExample(category, categoryExample);
        } else {
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        }
    }

    /**
     * 删除电子书分类的业务方法
     *
     * @param id : 要删除的电子书分类id
     * @author h0ss
     */
    public void delete(Long id) {
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        criteria.andIdEqualTo(id);
        categoryMapper.deleteByExample(categoryExample);
    }

    /**
     * 将电子书分类查询结果封装成CategoryQueryResp集合的业务方法
     * @param categoryList :
     * @return : java.util.List<cn.gpnusz.oliverwiki.resp.CategoryQueryResp>
     * @author h0ss
     */
    private List<CategoryQueryResp> getCategoryResp(List<Category> categoryList) {
        List<CategoryQueryResp> respList = new ArrayList<>();
        for (Category category : categoryList) {
            CategoryQueryResp categoryQueryResp = new CategoryQueryResp();
            BeanUtils.copyProperties(category, categoryQueryResp);
            respList.add(categoryQueryResp);
        }
        return respList;
    }
}
